/*
 * WMainView.java
 */

package tm.gui;

import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;

import agents.TrafficLightAgentCreator;

import com.jogamp.opengl.util.FPSAnimator;

import res.FixedRateAnimator;
import res.Util;
import res.exceptions.InvalidInputGraphException;
import res.input.GridGraphReader;
import tm.WMain;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.TimerTask;

import javax.media.opengl.awt.GLCanvas;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;

/**
 * The application's main frame.
 */
public class WMainView extends FrameView {
	
	public WMainView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        simulationTimer = new java.util.Timer();
        
        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = WMain.getApplication().getMainFrame();
            aboutBox = new WMainAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        WMain.getApplication().show(aboutBox);
    }
    
    @Action
    public void showNewSimDialog() {
        if (newSim == null) {
            JFrame mainFrame = WMain.getApplication().getMainFrame();
            newSim = new DNewSim(mainFrame, true);
            newSim.setLocationRelativeTo(mainFrame);
        }
        WMain.getApplication().show(newSim);
        
        if(newSim.getReturnStatus() == DNewSim.RET_OK) {
        	try {
        		GridGraphReader reader = new GridGraphReader(newSim.getSelectedFile());
        		
        		Util.Simulation.maxRedTime = newSim.getMaxRedTime();
        		Util.Simulation.minGreenTime = newSim.getMinGreenTime();
        		Util.Simulation.refreshTime = newSim.getRefreshTime();
        		Util.Simulation.flowInitial = newSim.getInitialFlow();
        		Util.Simulation.flowModif = newSim.getFlowModifier();
        		Util.Simulation.flowRate = newSim.getFlowRate();
        		
        		TrafficLightAgentCreator creator = new TrafficLightAgentCreator(reader);
        		
        		int remainder = newSim.getInitialFlow();
        		int agent;
        		while(remainder > 0) {
        			agent = Util.getRandom().nextInt(Util.Simulation.agents.size());
        			
        			if(Util.Simulation.agents.get(agent).getEdge().increaseLoad(1.0))
        				remainder--;
        		}

        		creator.startAgents();
        		canvas.removeGLEventListener(GridRoadRenderer.getInstance());
        		GridRoadRenderer.initRenderer(Util.Simulation.agents, reader.getGridWidth(), reader.getGridHeight());
        		canvas.addGLEventListener(GridRoadRenderer.getInstance());
        		
        		if(simulationTask != null)
        			simulationTask.cancel();
        		
        		simulationTask = new SimulationTask();
        		simulationTimer.schedule(simulationTask, 0, Util.Simulation.refreshTime);
        		
        		if(anim != null)
        			anim.stop();
        		anim = new FixedRateAnimator(canvas, Util.Simulation.refreshTime);
        		canvas.setVisible(true);
        		anim.start();
        	} catch (InvalidInputGraphException e) {
        		JOptionPane.showMessageDialog(this.getComponent(), resourceMap.getString("WMainView.invalidinputMSG"), resourceMap.getString("WMainView.invalidinputTitle"), JOptionPane.ERROR_MESSAGE);
        	} catch (IOException e) {
        		JOptionPane.showMessageDialog(this.getComponent(), resourceMap.getString("WMainView.ioerrorMSG"), resourceMap.getString("WMainView.ioerrorTitle"), JOptionPane.ERROR_MESSAGE);
			} catch (NumberFormatException e) {
				JOptionPane.showMessageDialog(this.getComponent(), resourceMap.getString("WMainView.invalidoptMSG"), resourceMap.getString("WMainView.invalidoptTitle"), JOptionPane.ERROR_MESSAGE);
			}
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        canvas = new GLCanvas();
        mainPanel = new javax.swing.JPanel();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        newMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N
        
        canvas.setName("canvas"); // NOI18N
        canvas.setVisible(false);

        GridRoadRenderer.initRenderer(null, 0, 0);
        
        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(canvas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(canvas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(tm.WMain.class).getContext().getActionMap(WMainView.class, this);
        newMenuItem.setAction(actionMap.get("showNewSimDialog")); // NOI18N
        newMenuItem.setText(resourceMap.getString("newMenuItem.text")); // NOI18N
        newMenuItem.setName("newMenuItem"); // NOI18N
        fileMenu.add(newMenuItem);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 216, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem newMenuItem;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;

    private final ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(tm.WMain.class).getContext().getResourceMap(WMainView.class);
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final java.util.Timer simulationTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
    private DNewSim newSim;
    private GLCanvas canvas;
    private FixedRateAnimator anim;
    private TimerTask simulationTask = null;


    private class SimulationTask extends TimerTask {

		@Override
		public void run() {
			int agent = Util.getRandom().nextInt(Util.Simulation.agents.size());
			boolean act = Util.getRandom().nextBoolean();
			boolean increase = Util.getRandom().nextBoolean();
			
			while(act && increase && Util.Simulation.agents.get(agent).getEdge().increaseLoad(Util.Simulation.flowModif))
				agent = Util.getRandom().nextInt(Util.Simulation.agents.size());
			
			while(act && !increase && Util.Simulation.agents.get(agent).getEdge().decreaseLoad(Util.Simulation.flowModif))
				agent = Util.getRandom().nextInt(Util.Simulation.agents.size());
		}

	}
    
}
